<jsp:directive.page session="true" />
<%@ page import="org.biojava.services.das.dao.RegistryUser"%>
<%@ page import="org.biojava.services.das.registry.UserManager"%>
<%@ include file="sangerheader.jsp"%>
<%
	

	email = (String) session.getAttribute("email");

	if (email == null) {
		
		email = (String) session.getAttribute("email-tbc");
	
		if ( email == null ) {
			response.sendRedirect("login.jsp");
			return;
		}		
	}

	
	String action = request.getParameter("action");
System.out.println("action="+action);

	if (action == null) {
		//if no action but user is already known we dont want to create a new user but just to log them in.
		if(!um.isNewUser(email)){
			response.sendRedirect("index.jsp");
			return;
		}
		
		action = "create";
	}

	System.out.println(action + " " + email);

	String watchdog = request.getParameter("watchdog");

	boolean alertMe = false;

	if ((watchdog != null) && (watchdog.equals("1"))) {
		alertMe = true;
	}

	if (action.equals("create")) {

		if ( (email == null) || (! um.isValidEmail(email))) {
			//System.out.println("redirecting!");
			session.setAttribute("message","Please provide a valid email!");
			response.sendRedirect("loginFirst.jsp");
			return;
		} else {
			//System.out.println("got a valid new email " + email);

			user = new RegistryUser();
			user.setOpenID(email);
			user.setEmail(email);
			user.setAlertMe(alertMe);
			um.createNewUser(user);
			
			// now confirming the session attribute
			session.removeAttribute("email-tbc");
			session.setAttribute("email",email);
			
			String from_page = (String)session.getAttribute("from_page");
			if ( from_page != null ) {
				session.removeAttribute("from_page");
				response.sendRedirect(from_page);
			} else {			
				response.sendRedirect("loginSettings.jsp");
			}
			
			return;

		}
	} else if (action.equals("update")) {

		if (!um.isValidEmail(email)) {
			session.setAttribute("message","Please provide a valid email!");
			response.sendRedirect("loginSettings.jsp");
			return;
		}

		String newId = request.getParameter("newemail");

		if ((newId == null) || (newId.equals(""))) {
			response
			.sendRedirect("loginSettings.jsp?message=You did not provide a new email!");
		} else {
			String uids = request.getParameter("user_id");
			response.sendRedirect("loginSettings.jsp");
			if (uids != null) {
		try {
			int uid = Integer.parseInt(uids);

		 user = um.getUserById(uid);
			user.setOpenID(newId);
			user.setEmail(email);
			user.setAlertMe(alertMe);
			um.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
			}

		}

	} else if (action.equals("delete")) {

	 user = um.getUser(email);
		session.setAttribute("message","Your email account has been deleted");
		response.sendRedirect("login.jsp?logout=true");
		um.deleteUser(user);
		return;

	}

	// default view is to jump to the settings page
%>

